#include "rtc.h"

static int init[RTC_ALARMS_COUNT] = {-1, -1, -1, -1, -1, -1};
static int counters[RTC_ALARMS_COUNT] = {-1, -1, -1, -1, -1, -1};
static int alarms[RTC_ALARMS_COUNT] = {1, 1, 1, 1, 1, 1};

void rtc_isr(void)
{
  if (ILR & ILR_RTCCIF_MASK)
  {
    for (int i = 0; i < RTC_ALARMS_COUNT; i++){
      if (init[i] == -1) continue;

      counters[i] += 1;
      if (counters[i] > init[i]) counters[i] = 0, alarms[i] += 1;
    }
  }
  ILR = 0x00000001;
}


void rtc_enable()
{
  PCONP |= 0x200; //Enable power for RTC
  CCR = 0x12;     //CTC reset and select RTC clock from 32 Khz.oscillator
  ILR = 0xFF;     //Clear RTC interrupt register
  AMR = 0xFF;     //Disable all the alrams.
  CIIR = 0x01;    //Enable only second count interrupt. One second interrupt.
  CISS = 0;       //Disable all subsecond interrupts.
  CCR = 0x11;     //Enable RTC

  ctl_set_isr(VICIRQStatus_RTC_BIT, 1, CTL_ISR_TRIGGER_FIXED, rtc_isr, 0);
  ctl_unmask_isr(VICIRQStatus_RTC_BIT);

  return;
}

void rtc_set_time(datetime_t time)
{
  CCR &= 0xFE;
  SEC = time.second;
  MIN = time.minute; //  Minute value [0-59]
  HOUR = time.hour; //  Hour value [0-23]
  DOM = time.day; //  Day of month value [1-31]
  MONTH = time.month; //  Month value [1-12]
  YEAR = time.year; //  Year value
  CCR |= 0x01;
  return;
}

datetime_t rtc_get_time(void)
{
  datetime_t time;
  time.second = ((CTIME0 & 0x0000003F)>>0);
  time.minute = ((CTIME0 & 0x00003F00)>>8);
  time.hour = ((CTIME0 & 0x001F0000)>>16);
  time.day = ((CTIME1 & 0x0000001F)>>0);
  time.month = ((CTIME1 & 0x0000FF00)>>8);
  time.year = ((CTIME1 & 0x0FFF0000)>>16);
  CCR |= 0x01;
  return (time);
}



void rtc_alarm_set(unsigned int id, int period)
{
  assert(id < RTC_ALARMS_COUNT);
  init[id] = period;
  counters[id] = 0;
}

bool rtc_alarm_get(unsigned int id)
{
  assert(id < RTC_ALARMS_COUNT);
  int ret = alarms[id];
  alarms[id] = 0;
  return ret > 0;
}



